clear all
set type double
global fdr_in_global = 0

cap erase ../data/rd_results.dta
set seed 128818

cap program drop drawgraph_sub
program drawgraph_sub, eclass
	* DAYS "90" "180"
	args outcomevar runningvar condition DAYS graph_i GRAPH TABLE buyer
	keep if abs(`runningvar') < . 
	if "`condition'" ~= ""{
		keep if `condition'
		local condition_f = ustrregexra("`condition'","[\s\=\!\.\,\&]","")
	}
	pause on
	foreach days in `DAYS'{
		cap drop flag_tmp
		gen flag_tmp = 0
		sum `runningvar' if `runningvar' < 0, d
		replace flag_tmp = 1 if `runningvar' < `r(p10)'
		sum `runningvar' if `runningvar' > 0, d
		replace flag_tmp = 1 if `runningvar' > `r(p90)' & `runningvar' < .
		*di "AAAA"
		di "`outcomevar'`days' "
		di "`runningvar'"
		rdrobust `outcomevar'`days' `runningvar' ///
			if `runningvar' ~= 0 & flag_tmp == 0, vce(nncluster contract_id)
		if $fdr_in_global == 1{
			di "*******************************************"
			di "************* fdr_`buyer'_`days'_: ${fdr_`buyer'_`days'_} ****"
			di "*******************************************"
			ereturn scalar fdr = ${fdr_`buyer'_`days'_}
		}
		if _rc == 0{
			local tau = strofreal(`e(tau_bc)', "%9.2g")
			local pv = strofreal(`e(pv_rb)',"%9.2g")
			local obs = strofreal(`e(N_l)' + `e(N_r)',"%9.0fc")
			local hr = strofreal(`e(h_l)',"%9.2g")
			local hl = strofreal(`e(h_r)',"%9.2g")
			local se_tau = strofreal(`e(se_tau_rb)',"%9.2g")
			mat B_left =  e(beta_p_l)
			mat B_right =  e(beta_p_r)
		}
		local t = round(`days' / 30)
		if `t' > 1{
			local months = "s"
		}
		ereturn scalar p = `e(pv_rb)'
		
		*est sto t`outcomevar'`days'`runningvar'`condition_f'
		*local TABLE = "`TABLE' t`outcomevar'`days'`runningvar'`condition_f'"
		est sto t`buyer'_`days'
		local TABLE "`TABLE' t`buyer'_`days'"
		local star10 = ""
		if `e(pv_rb)' <= .01{
			local star10 = "***"
		}
		else if `e(pv_rb)' <= .05{
			local star10 = "**"
		}
		else if `e(pv_rb)' <= .1{
			local star10 = "*"
		}

		preserve		/*calculate fdr*/
			local exists = 0
			cap noisily use ../data/rd_results, clear
			if _rc == 0{
				qui count if (buyer == "`buyer'") & (days == `days') ///
				& (runningvar == "`runningvar'") & outcomevar == "`outcomevar'" ///
				& pv == `e(pv_rb)' & condition == "`condition'"
				local exists = r(N)
			}
			if `exists' ==0{
				clear
				set obs 1
				gen buyer = "`buyer'"
				gen days = `days'
				gen runningvar = "`runningvar'"
				gen outcomevar = "`outcomevar'"
				gen pv = `e(pv_rb)'
				gen tau =`e(tau_bc)'
				gen se =`e(se_tau_rb)'
				gen datetime = "$S_TIME  $S_DATE"
				gen condition = "`condition'"
				cap append using ../data/rd_results
				sleep 1000
				save ../data/rd_results, replace
			}
		restore
		*local star10 = " "
		if `graph_i' == 1{
			cap graph drop u`days'_`runningvar'
			rdplot `outcomevar'`days' `runningvar' if abs(`runningvar') < $threshold_fg & ///
			`runningvar' ~= 0,  ///
			graph_options(title("`days' Days", size(large)) name(u`days'_`runningvar') ///
				legend(off) xtitle( {&Delta}) ///
				subtitle("winners　　　　　losers", size(medium) ring(5) margin(zero)) ///
				/*ytitle(`outcomevar_label')*/ ylabel(, angle(0) format(%3.1g)) ///
				graphregion(color(white) lcolor(none)))
		}	
		local outcomevar_label : variable label `outcomevar'`days'
		if `graph_i' == 2{
			cap graph drop u`days'_`runningvar'
			rdplot `outcomevar'`days' `runningvar' if abs(`runningvar') < $threshold_fg & ///
						`runningvar' ~= 0, p(1) h( ) ///
			graph_options(title("`days' Days", size(large)) name(u`days'_`runningvar') legend(off) ///
				xtitle({&Delta}) graphregion(color(white) lcolor(none)) ///
				/*t2title("From_`start_day'" "Thru_`end_day'", ///
					size(small) place(nw) ring(1))*/ ///
				subtitle("winners　　　　　losers", size(medium) ring(5) margin(zero)) ///
				t2title("{it:{&beta}}({it:se}):`tau'(`se_tau')`star10'", ///
					size(small) place(ne) ring(5) margin(zero)) ///
				ylabel(/*0(.2)1*/, angle(0) format(%3.1g)) /*ytitle(`outcomevar_label')*/ ///
				t1title("{it:h} = `hl'; {it:N} = `obs'", size(small) place(ne) margin(zero) height(.01) ring(5)))

		}
		if `graph_i' == 3{
			cap graph drop u`days'_`runningvar'
			rdplot `outcomevar'`days' `runningvar' if abs(`runningvar') < $threshold_fg & ///
			`runningvar' ~= 0, genvars hide 
			twoway(scatter rdplot_mean_y rdplot_mean_x, ///
			title("`days' Days", size(large)) name(u`days'_`runningvar') ///
				legend(off) xtitle( {&Delta}) mc(gs10) xline(0,lc(black)) ///
				subtitle("winners　　　　　losers", size(medium) ring(5) margin(zero)) ///
				/*ytitle(`outcomevar_label')*/ ylabel(, angle(0) format(%3.1g)) ///
				graphregion(color(white) lcolor(none))) ///
			(function y = B_right[2,1]*x + B_right[1,1], range(0 .02) lwidth(thick) lc(gs4) lpattern(longdash)) ///
			(function y = B_left[2,1]*x + B_left[1,1], range(-.02 0) lwidth(thick)  lc(gs4) lpattern(longdash))
			cap drop rdplot_*
		}	
		
		if `graph_i' > 0{
			local GRAPH = "`GRAPH' u`days'_`runningvar'"
		}
	}
	di as result `"`GRAPH'"'
	ereturn local GRAPH `"`GRAPH'"'
	ereturn local TABLE `"`TABLE'"'
end


/**/
global threshold_rd = .2
global threshold_fg = .02

set seed 12901

use ../data/indonesia/xyz.dta, replace /* NAT==1only */
set seed 1002928
/* auctions in which the lowest bidder wins*/
cap drop temp

drop if z_konsultan == 1 

rename delta2 delta_win1 
rename delta2_p delta_win2  
rename delta delta_low1 
rename delta_p delta_low2  
gen Eprocurement = (z_proc_type == "SEP")
bys z_state_name: egen Ep_state = max(Eprocurement)
gen non_EP = (Ep_state == 1 & Eprocurement == 0)

*Note:tabulation of N of auction by stata & year 　　  
tab z_state_name z_year if  winner == 1 


/* indonesia */
local buyer = "Indonesia"
/* main*/
foreach d in "30" "60" "90" "120" "180" "365"{
	gen blogm`d' = blog`d' / 1000000
}


*drop if bid_date ==  15856 
sum bid_date if z_final_rank == 1, detail
gen median_date = r(p50)
gen start_date = r(min)
gen end_date = r(max)
format start_date median_date end_date bid_date %td
gen sample_before = (bid_date <= median_date) 

tab Eprocurement if sample_before == 1  & z_final_rank == 1

gen sample_after = (bid_date > median_date) if bid_date !=.
tab Eprocurement if sample_after == 1 & z_final_rank == 1
local condition = ""
preserve
	drawgraph_sub lnblog delta_low1 "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
restore
preserve
	drawgraph_sub lnblog delta_low1 "Eprocurement == 0" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
restore
preserve
	drawgraph_sub lnblog delta_low1 "Eprocurement == 1" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
restore

************** georgia ****************
use ../data/georgia/sample_georgia26may22.dta, clear
rename est reserve
rename pct_winbid win_bid_pct 
rename bid_rank_first bid_rank
rename bid_first bid
gen est = .

qui gen delta_low1 = delta_first
cap graph drop Georgia
keep if pct_bid_first >= .85 & pct_bid_first < .
local buyer = "Georgia"
local condition = ""
drawgraph_sub lnblog delta_low1 "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'"

************** mongolia *******************
use ../data/mongolia/sample_mongolia_30jun22.dta, clear
gen reserve = .
gen win_bid_pct = .
replace winbid = winbid / 1000000
replace reserve = reserve / 1000000
gen est = .
qui gen delta_low1 = delta1

local buyer = "Mongolia"
local condition = ""
drawgraph_sub lnblog delta_low1 "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 

************** malta *******************
use ../data/malta/malta, clear
keep if Evaluation_Method == "Price/Cost Effectiveness" & eAuctions=="No"
gen reserve = .
gen win_bid_pct = .
qui bys firm_id: gen N_participations = _N
qui bys contract_id: gen N_bids = _N
sort contract_id winbid
gen est = .

qui gen delta_low1 = delta

bys contract_id: replace winbid = winbid[_n - 1] if winbid[_n - 1] < .
bys contract_id: replace win_bid_pct = win_bid_pct[_n - 1] if win_bid_pct[_n - 1] < .

local buyer = "Malta"
local condition = ""
drawgraph_sub lnblog delta_low1 "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
	
************** california *******************
use ../data/caltrans/sample_caltrans29Dec24.dta, clear

rename delta delta_low1
rename delta23 delta_low2

local buyer = "California"
local condition = ""
drawgraph_sub lnblog delta_low1 "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
/**/



tempfile tempf001
clear
save `tempf001', replace empty
use ../data/rd_results, clear
egen group = group(days runningvar outcomevar condition), missing

pause on
sort group pv
keep if condition == ""

foreach days in  "30" "60" "90" "120"{
	preserve
		keep if days == `days'
		rename pv pval
		do "fdr_sharpened_qvalues_Anderson2007.do"
		*pause
		append using `tempf001'
		sleep 1000
		save `tempf001', replace
	restore
}

use `tempf001', clear
rename bky06_qval q
save "../data/fdr", replace
di "end of fdr calculations"

use "../data/fdr", clear
qui sum q
local N_fdr_results = r(N)
global fdr_in_global = 1
di `N_fdr_results'
forvalues x = 1(1)`N_fdr_results'{
	if condition[`x'] == ""{
		local buyer = buyer[`x']
		local days = days[`x']
		local condition = condition[`x']
		local q = q[`x']
		di buyer[`x'] _continue
		di days[`x'] 
		di q[`x']
		global fdr_`buyer'_`days'_`condition' = `q'
		global pv_`buyer'_`days'_`condition' = pv[`x']
	}
}

global threshold_fg = .01
do load_dataset.do
foreach outcomevar in /*"lnflog "*/ "lnblog" /*"blog" "cum_win" "rblog"*/{
	foreach runningvar in "delta_low1" /*"delta_low2"*/ { 
		/* indonesia*/
		/*Table 3: RD Estimates for Log Backlog: Public Works Auctions in Indonesia */ 
		use ../data/indonesia/xyz.dta, replace /* NAT==1only */
		set seed 1002928
		cap drop temp
		local buyer = "Indonesia"
		drop if z_konsultan == 1 
		rename delta2 delta_win1 
		rename delta2_p delta_win2  
		rename delta delta_low1 
		rename delta_p delta_low2  
		gen Eprocurement = (z_proc_type == "SEP")
		bys z_state_name: egen Ep_state = max(Eprocurement)
		gen non_EP = (Ep_state == 1 & Eprocurement == 0)

		*Note:tabulation of N of auction by stata & year 　　  
		tab z_state_name z_year if  winner == 1 

		drawgraph_sub `outcomevar' `runningvar' "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
		foreach e in `e(TABLE)' {
			local TABLE_combined = "`TABLE_combined' `e'"
		}
			
		esttab `TABLE_combined' using ../Output/Table3.tex, ///
		f replace collabels(none) title("`runningvar'") nonumbers cells(none) starlevels(* 0.10 ** 0.05 *** 0.01)  ///
		stats(tau_bc se_tau_rb p fdr h_r /*b_l *kernel bwselect*/ N, fmt(/*%6.0g*/3 3 3 3 3 "%9.0fc" ) ///
		labels(`"\raisebox{-2.3mm}[0mm][0mm]{$\hat{\beta}$}"' `" "' `"\it{p-value}"' `"\it{q}"' `"\it{h}"' `"Obs."') ///
		layout(@ (@) [@] @ @ @) star(tau_bc)) ///
		mtitles("30 Days" "60 Days" "90 Days" "120 Days") ///

		local TABLE_combined = ""
		

		/* other 4 buyers */
		/*Table 8: RD Estimates of Log Backlog for Four Countries: Georgia, Mongolia, Malta and California */ 

		foreach buyer in "Georgia" "California" "Malta" "Mongolia" {
			di "*************** `buyer' *****************"
			if "`buyer'" == "Georgia"{
				use ../data/georgia/sample_georgia26may22.dta, clear /* NAT==1only */
				qui gen delta_low1 = delta_first
				qui gen delta_low2 = delta23_first
				qui gen delta_win1 = deltaw_first
				qui gen delta_win2 = deltaw23_first
			}
			else if "`buyer'" == "California"{
				use ../data/caltrans/sample_caltrans29Dec24.dta, clear
				rename delta delta_low1
				rename delta23 delta_low2
				
			}
			else if "`buyer'" == "Malta"{
				local TABLE_combined = ""
				use ../data/Malta/malta.dta, clear
				keep if Evaluation_Method == "Price/Cost Effectiveness" & eAuctions=="No"
				rename deltap delta_win1
				rename delta2p delta_win2
				rename delta delta_low1
				rename delta2 delta_low2

			}
			else if "`buyer'" == "Mongolia"{				
				use ../data/mongolia/sample_mongolia_30jun22.dta, clear
				rename delta1w delta_win1
				rename delta2w delta_win2
				rename delta1 delta_low1
				rename delta2 delta_low2
			}
					
			drawgraph_sub `outcomevar' `runningvar' "`condition'" "30 60 90 120" "0" "`GRAPH'" "`TABLE'" "`buyer'" 
			foreach e in `e(TABLE)' {
				local TABLE_combined = "`TABLE_combined' `e'"
			}

			if ("`buyer'" == "California"){
				esttab `TABLE_combined' using ../Output/Table8.tex, ///.  
				f replace cells(none) collabels(none) title("`runningvar'") nonumbers ///
				stats(tau_bc se_tau_rb p fdr h_r /*b_l *kernel bwselect*/ N, fmt(/*%6.0g*/3 3 3 3 3 "%9.0fc" ) ///
				labels(`"\raisebox{-2.3mm}[0mm][0mm]{$\hat{\beta}$}"' `" "' `"\it{p-value}"' `"\it{q}"' `"\it{h}"' `"Obs."') ///
				layout(@ (@) [@] @ @ @) star(p) ) ///
				mtitles("30 Days" "60 Days" "90 Days" "120 Days" "30 Days" "60 Days" "90 Days" "120 Days") ///
				posthead(\\[-2mm] &\multicolumn{4}{c}{Georgia} & \multicolumn{4}{c}{Caltrans} \\ ///
				\cmidrule(l){2-5}   \cmidrule(l){6-9} \\ )

			}
			else if ("`buyer'" == "Mongolia") {
				esttab `TABLE_combined' using ../Output/Table8.tex, ///.  
				f append cells(none) collabels(none) title("`runningvar'") nonumbers ///
				stats(tau_bc se_tau_rb pv_rb fdr h_r /*b_l *kernel bwselect*/ N, fmt(/*%6.0g*/3 3 3 3 3 "%9.0fc" ) ///
				labels(`"\raisebox{-2.3mm}[0mm][0mm]{$\hat{\beta}$}"' `" "' `"\it{p-value}"' `"\it{q}"' `"\it{h}"' `"Obs."') layout(@ (@) @ @ @ @) ) ///
				nomtitles ///
				posthead(\\[-2mm] &\multicolumn{4}{c}{Malta} & \multicolumn{4}{c}{Mongolia} \\ ///
								\cmidrule(l){2-5}   \cmidrule(l){6-9})
				

			}
		}

	}
}
global fdr_in_global = 0




